package cn.xshi.job.command;

import cn.hutool.core.collection.CollectionUtil;
import cn.xshi.common.base.BaseService;
import cn.xshi.common.entity.ScheduleJob;
import cn.xshi.common.util.StringUtil;
import cn.xshi.job.publisher.ChannelUtil;
import cn.xshi.job.publisher.NettyUtil;
import cn.xshi.job.vo.ChannelEntity;
import cn.xshi.job.vo.JobHandlerEntity;
import cn.xshi.job.vo.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import javax.annotation.Resource;
import java.util.List;
import java.util.Random;
/**
 * 任务集中处理工厂
 */
@Slf4j
public class JobFactory extends BaseService implements Job {

	@Resource
    ChannelUtil channelUtil;

	@Resource
    NettyUtil nettyUtil;

	/**
	 * 执行操作
	 * @param context
	 * @throws JobExecutionException
	 */
	public void execute(JobExecutionContext context) throws JobExecutionException {
		ScheduleJob scheduleJob = (ScheduleJob) context.getMergedJobDataMap().get("scheduleJob");
		String clientGroupId = scheduleJob.getClientGroupId();
		String jobHandler = scheduleJob.getJobHandler();
		if(!StringUtil.isEmpty(clientGroupId) && !StringUtil.isEmpty(jobHandler)){
			List<ChannelEntity> channelEntities = channelUtil.get(clientGroupId);
			if(CollectionUtil.isNotEmpty(channelEntities)){
				send(channelEntities,scheduleJob);
			}
		}
		log.info("scheduleJob，{}",scheduleJob);
	}

	/**
	 *
	 * @param channelEntities
	 * @param scheduleJob
	 */
	public void send(List<ChannelEntity> channelEntities,ScheduleJob scheduleJob){
		try {
			/*
			String name = scheduleJob.getJobName();
			String id = scheduleJob.getJobId();
			String des = scheduleJob.getDesc();
			String clientId = scheduleJob.getClientId();
			String jobHandler = scheduleJob.getJobHandler();
			String jobPara = scheduleJob.getJobPara();
			String jobTitle = scheduleJob.getJobTitle();
			*/
			Random random = new Random();
			int size = random.nextInt(channelEntities.size());
			ChannelEntity channelEntity = channelEntities.get(size);
			RequestInfo requestInfo = new RequestInfo();
			requestInfo.setJobHandlerEntity(new JobHandlerEntity(scheduleJob.getJobHandler(),scheduleJob.getJobPara()));
			requestInfo.setObj(scheduleJob.getJobPara());
			channelEntity.setRequestInfo(requestInfo);
			nettyUtil.sendMessage(channelEntity);
		}catch (Exception e){
			e.printStackTrace();
			log.info("发送任务异常，{}",e);
		}
	}
}